<template>
  <el-container>
    <el-main>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
        <el-row>
          <el-col>
            <el-form-item prop="save">
              <el-input v-model="ruleForm.save" :disabled="true" @click="selectSavePath" placeholder="下载路径"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item prop="queryWord">
              <el-input v-model="ruleForm.queryWord" placeholder="搜索"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :sm="4">
            <el-form-item prop="hd">
              <el-checkbox v-model="ruleForm.hd">高清</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :sm="4">
            <el-form-item prop="lastest">
              <el-checkbox v-model="ruleForm.lastest">最新</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :sm="4">
            <el-form-item prop="lastest">
              <el-checkbox v-model="ruleForm.gif">动图</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :sm="12">
            <el-form-item prop="z">
              <el-select v-model="ruleForm.z" placeholder="请选择" @change="changeSize">
                <el-option key="0" label="全部尺寸" value="" >全部尺寸</el-option>
                <el-option key="1" label="小尺寸" value="1" >小尺寸</el-option>
                <el-option key="2" label="中尺寸" value="2" >中尺寸</el-option>
                <el-option key="3" label="大尺寸" value="3" >大尺寸</el-option>
                <el-option key="9" label="特大尺寸" value="9" >特大尺寸</el-option>
                <el-option key="cs" label="自定义尺寸" value="cs" >自定义尺寸</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="6">
            <el-form-item prop="width">
              <el-input :disabled="ruleForm.z === 'cs'?false:true" v-model="ruleForm.width" placeholder="长度"></el-input>
            </el-form-item>
          </el-col>
          <el-col :sm="6">
            <el-form-item prop="height">
              <el-input :disabled="ruleForm.z === 'cs'?false:true" v-model="ruleForm.height" placeholder="高度"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :sm="12">
            <el-form-item>
              <el-button style="width: 100%" type="primary" @click="submitForm('ruleForm')">开始爬取</el-button>
            </el-form-item>
          </el-col>
          <el-col :sm="12">
            <el-form-item>
              <el-button style="width: 100%" type="primary" @click="selectSavePath">选择保存地址</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        :data="imgArr"
        style="width: 100%"
        height="600"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          prop="name"
          label="名称"
          align="center"
          width="180">
        </el-table-column>
        <el-table-column
          label="图片"
          align="center"
        >
          <template slot-scope="scope">
            <div style="overflow-x: auto">
              <img :src="scope.row.src" style="height: 300px;" :alt="scope.row.name" @click="showBigImg">
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <el-button type="primary" @click="dowanloadOneImg(scope.row.name,scope.row.src,scope.row.down)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row>
        <el-col>
          <el-pagination
            @current-change="handleCurrentChange"
            :page-size="pageSize"
            :current-page.sync="pageNum"
            layout="prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-button style="width: 100%" :disabled="downButton" type="primary" @click="dowanloadImg">下载图片</el-button>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script>
  import { ipcRenderer } from 'electron'
  import request from 'request'
  import deciphe from '@/utils/deciphe'

  const dialog = require('electron').remote.dialog
  const imgBase64 = 'data:image/jpeg;base64,'
  export default {
    name: 'index',
    data: function () {
      return {
        pageNum: 1,
        pageSize: 100,
        total: 0,
        downButton: true,
        imgArr: [],
        multipleSelection: [],
        ruleForm: {
          queryWord: '',
          save: localStorage.getItem('savePath') !== null ? localStorage.getItem('savePath') : '',
          hd: false,
          lastest: false,
          gif: false,
          z: '',
          width: 1920,
          height: 1080
        },
        rules: {
          queryWord: [
            { message: '请输入网络地址', trigger: 'blur' }
          ],
          save: [
            { message: '请选择保存地址', trigger: 'blur' }
          ]
        }
      }
    },
    created: function () {
      ipcRenderer.on('downComplete', (event, arg) => {
        this.$message.success(arg + '下载完成')
      })
    },
    methods: {
      changeSize: function (val) {
        this.ruleForm.z = val
        console.log(val)
        if (!val) {
          this.isCustomSize = true
        }
      },
      handleCurrentChange: function (val) {
        this.pageNum = val
        this.submitForm('ruleForm')
      },
      submitForm (formName) {
        var that = this
        ipcRenderer.send('request', 'ping')
        this.$refs[formName].validate((valid) => {
          const imgArr = []
          try {
            if (valid) {
              // console.log(this.ruleForm.url)
              const queryWord = that.ruleForm.queryWord ? encodeURIComponent(that.ruleForm.queryWord) : encodeURIComponent('图片')
              const rn = that.pageSize
              const pn = (that.pageNum - 1) * that.pageSize
              const hd = that.ruleForm.hd ? 1 : 0
              const lastest = that.ruleForm.lastest ? 1 : 0
              const lm = that.ruleForm.gif ? 6 : -1
              const z = that.ruleForm.z
              const customWidth = that.ruleForm.z === 'cs' ? that.ruleForm.width : ''
              const customHeight = that.ruleForm.z === 'cs' ? that.ruleForm.height : ''
              // console.log('图尺寸' + that.ruleForm.z)
              // console.log('搜索词' + that.ruleForm.queryWord)
              // console.log('每页条数' + rn)
              // console.log('页码' + pn)
              request({
                url: `http://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord=${queryWord}&cl=2&lm=${lm}&ie=utf-8&oe=utf-8&adpicid=&st=&z=${z}&ic=&hd=${hd}&latest=${lastest}&copyright=&word=${queryWord}&s=&se=&tab=&width=${customWidth}&height=${customHeight}&face=&istype=&qc=&nc=&fr=&expermode=&force=&gsm=&1569202875333=&pn=60&rn=50&pn=${pn}&rn=${rn}`,
                methods: 'GET',
                headers: {
                  'Content-type': 'application/json'
                },
                json: true
              }, function (error, response, allBody) {
                if (!error && response.statusCode === 200) {
                  // allBody = JSON.parse(allBody)
                  console.log(allBody) // 请求成功的处理逻辑
                  // console.log(deciphe(allBody.data[0].fromURL))
                  // console.log(deciphe(allBody.data[0].objURL))

                  // console.log(Array.isArray(allBody.data))
                  that.total = allBody.listNum
                  for (let i = 0; i < allBody.data.length; i++) {
                    (function (j) {
                      if (allBody.data[j].thumbURL !== undefined) {
                        // console.log(allBody.data[j].thumbURL)
                        request({
                          url: allBody.data[j].thumbURL,
                          methods: 'GET',
                          headers: {
                            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36',
                            'Referer': 'http://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=gb18030&word=%CD%BC%C6%AC&fr=ala&ala=1&alatpl=others&pos=0'
                          },
                          encoding: null
                        }, function (error, response, body) {
                          if (!error && response.statusCode === 200) {
                            // console.log(body) // 请求成功的处理逻辑
                            // http//pic26.nipic.com/20130121/9252150_101440518391_2.jpg
                            const down = 'https://image.baidu.com/search/down?tn=download&ipn=dwnl&word=download&ie=utf8&fr=result&url=' + encodeURIComponent(deciphe(allBody.data[j].objURL)) + '&thumburl=' + encodeURIComponent('https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/' + allBody.data[j].thumbURL.split('/it/')[1])
                            // console.log(down)
                            imgArr.push({name: allBody.data[j].fromPageTitleEnc.replace('图片', ''), src: imgBase64 + body.toString('base64'), url: allBody.data[j].thumbURL, down})
                          }
                        })
                      }
                    })(i)
                  }
                  that.imgArr = imgArr
                  // console.log(that.imgArr)
                }
              })
            } else {
              console.log('error submit!!')
              return false
            }
          } catch (e) {
            console.log(e)
          }
        })
        // console.log(that.imgArr)
      },
      handleSelectionChange (val) {
        // console.log(val)
        this.multipleSelection = val
      },
      dowanloadImg: function () {
        var that = this
        for (let i = 0; i < that.multipleSelection.length; i++) {
          (function (j) {
            that.dowanloadOneImg(that.multipleSelection[j].name, that.multipleSelection[j].src)
          })(i)
        }
      },
      dowanloadOneImg: function (name, src, down) {
        name = this.ruleForm.save + '\\' + name + Date.now() + '.jpg'
        src = src.replace(imgBase64, '')
        console.log(down)
        ipcRenderer.send('download', {name, src, down})
        // fs.writeFile(name, Buffer.from(src.replace(imgBase64, ''), 'base64'), function (err) {
        //   if (err) {
        //     that.$message.error(err.text)
        //     throw err
        //   }
        //   that.$message.success(name + '下载完成')
        // })
      },
      selectSavePath: function () {
        const that = this
        dialog.showOpenDialog({
          title: '选择要上传的文件（支持多选）',
          properties: ['openDirectory']
        }, (filePaths) => {
          // filePaths:用户选择的文件路径的数组
          console.log(filePaths)
          if (filePaths !== undefined) {
            that.ruleForm.save = filePaths[0]
            localStorage.setItem('savePath', filePaths[0])
          }
        })
      },
      // 放大图片
      showBigImg: function (e) {
        // console.log(e)
        if (e.target.style.zIndex === '99') {
          e.target.style.transition = 'all 1.5s ease'
          e.target.style.position = 'relative'
          e.target.style.zIndex = '0'
          e.target.style.height = '300px'
        } else {
          e.target.style.position = 'fixed'
          e.target.style.transition = 'all 1.5s ease'
          e.target.style.zIndex = '99'
          e.target.style.height = window.screen.height / 2 + 'px'
          e.target.style.width = 'auto'
          e.target.style.left = '0px'
          e.target.style.top = '0px'
        }
      }
    },
    watch: {
      multipleSelection: function () {
        this.downButton = !(this.multipleSelection.length > 0)
      }
    }
  }
</script>

<style scoped>

</style>
